package com.das.mechanic_alone.mvp.presenter.alone;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.text.TextUtils;

import com.das.mechanic_alone.mvp.contract.alone.X3AloneContract;
import com.das.mechanic_alone.mvp.view.alone.X3AloneActivity;
import com.das.mechanic_base.base.X3BaseCallModel;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.alone.AloneImageAndRecordBean;
import com.das.mechanic_base.bean.alone.AloneNewBean;
import com.das.mechanic_base.bean.alone.TestRecommendBean;
import com.das.mechanic_base.bean.common.AwsFileBean;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.bean.greendao.AloneServiceNewBean;
import com.das.mechanic_base.def.alone.AloneUploadStatus;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.X3AloneLayoutUtils;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3StringUtils;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * Created by chenSi on 2018/3/13.
 */

public class X3AlonePresenter extends X3BasePresenter<X3AloneContract.View> implements X3AloneContract.Presenter{

    private AloneNewBean aloneBean;

    @Override
    public void start() {
        getDetectionServiceList();
    }

    private void obtainAloneBean(final List<AloneServiceListBean> serviceListBeans) {
        NetWorkHttp.getApi().obtainAloneBean(mView.providerWorkBaseId(), mView.providerToSystemId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<AloneNewBean>() {
                    @Override
                    protected void onDone(AloneNewBean aloneBeans) {
                        /**
                         * 将网络上获取的购物车数据 存储到本地
                         */
                        //mView.saveService(serviceListBeans);
                        if (aloneBeans != null) {
                            aloneBean = aloneBeans;
                            mView.getEvaluationContent(aloneBeans.evaluation + "");
                            mView.showCurrenMiles(aloneBeans.currentMiles,aloneBeans.perMiles);
                            mView.saveService(serviceListBeans);
                            mView.saveSoundId(aloneBeans.evaluationSoundId);
                            mView.switchAloneSystem(aloneBeans.itemQuestionList,true);
                        }

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void providerAloneBean() {
        mView.submitAlone(aloneBean.itemQuestionList);
    }

    /**
     * 更新精检图片
     * @param resId
     * @param titleIndex
     */
    @Override
    public void saveOrUpdateWorkResource(long resId,long titleIndex,boolean isUpload,String path) {
        /**
         * 如果resId == 0 说明上传失败直接回调
         */
        if (resId == 0) {
            mView.getUpdatePictureSuccess(new AloneImageAndRecordBean(path,"",resId, AloneUploadStatus.UPLOADING_FAILED),titleIndex,isUpload);
            return;
        }

        Boolean viewFinishing = mView.isViewFinishing();
        if (viewFinishing == null || viewFinishing) {
            return;
        }
        List<AloneNewBean.ItemQuestionListBean> itemQuestionListBeans = mView.providerAloneNewBeans();
        if (X3StringUtils.isListEmpty(itemQuestionListBeans)) {
            return;
        }
        if (titleIndex >= itemQuestionListBeans.size()) {
            return;
        }

        NetWorkHttp.getApi().saveOrUpdateWorkResource(itemQuestionListBeans.get((int) titleIndex).id,resId,0,mView.providerWorkBaseId(),!isUpload)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<String>() {
                    @Override
                    protected void onDone(String imagePath) {
                        mView.getUpdatePictureSuccess(new AloneImageAndRecordBean(path,imagePath,resId,AloneUploadStatus.UPLODING),titleIndex,isUpload);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        /**
                         * 如果resId == 0 说明上传失败直接回调
                         */
                        mView.getUpdatePictureSuccess(new AloneImageAndRecordBean(path,"",resId, AloneUploadStatus.UPLOADING_FAILED),titleIndex,isUpload);
                    }
                });
    }

    @Override
    public void getDetectionServiceList() {
        NetWorkHttp.getApi().getTouchServiceList(mView.providerWorkBaseId())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<List<AloneServiceNewBean>>() {
                    @Override
                    protected void onDone(List<AloneServiceNewBean> mList) {
                        if (X3StringUtils.isListEmpty(mList)) {
                            obtainAloneBean(new ArrayList<>());
                            return;
                        }

                        obtainAloneBean(X3AloneLayoutUtils.getCurrentServiceList(mList));
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void getDetectionServiceListForRefresh() {
        NetWorkHttp.getApi().getTouchServiceList(mView.providerWorkBaseId())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<List<AloneServiceNewBean>>() {
                    @Override
                    protected void onDone(List<AloneServiceNewBean> mList) {
                        if (X3StringUtils.isListEmpty(mList)) {
                            mView.getDetectionServiceListForRefresh(new ArrayList<>());
                            return;
                        }

                        mView.getDetectionServiceListForRefresh(X3AloneLayoutUtils.getCurrentServiceList(mList));
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void saveDetectionServiceList(List<AloneServiceListBean> mList) {

        NetWorkHttp.getApi().saveDetectionServiceList(mList,mView.providerWorkBaseId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        providerAloneBean();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void saveDetectionService(List<AloneServiceListBean> mList) {
        NetWorkHttp.getApi().saveDetectionServiceList(mList,mView.providerWorkBaseId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void uploadWavAws(File wavFile,String id) {
        try {
            RequestBody requestBody = RequestBody.create(MediaType.parse("audio/*"), wavFile);
            String filename = URLEncoder.encode(wavFile.getName(), "UTF-8");
            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            Map<String,RequestBody> map = new HashMap<>();

            map.put("description",RequestBody.create(MediaType.parse("multipart/form-data"), "技师评论"));

            map.put("ossBucketName",RequestBody.create(MediaType.parse("multipart/form-data"), "SERVICE_PIC"));

            NetWorkHttp.getApi().uploadFileAws(map,fileBody,new HashMap<>())
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<AwsFileBean>() {
                        @Override
                        protected void onDone(AwsFileBean awsFileBean) {
                            mView.getAwsSoundIdSuccess(true,awsFileBean,id);
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {
                            mView.getAwsSoundIdSuccess(false,null,id);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void uploadImageAws(File imgFile,long titleIndex) {
        if (!imgFile.exists()) {
            return;
        }

        if (mView.getContext() == null) {
            return;
        }
        X3AloneActivity context = (X3AloneActivity) mView.getContext();
        if (context.isFinishing()) {
            return;
        }

        if (imgFile.getPath().endsWith(".mp4") || imgFile.getPath().endsWith(".mov")) {
            uploadNewFile(imgFile,X3FileUtils.getFileLastModifiedTime(imgFile),titleIndex,imgFile.getPath());
        }else {
            try {
                Luban.with(mView.getContext())
                        .load(imgFile.getPath())
                        .ignoreBy(100)
                        .setTargetDir(X3FileUtils.getStoragePath(mView.getContext(), X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH))
                        .filter(path -> !(TextUtils.isEmpty(imgFile.getPath()) || imgFile.getPath().toLowerCase().endsWith(".gif")))
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess(File file) {
                                uploadNewFile(file,X3FileUtils.getFileLastModifiedTime(imgFile),titleIndex,imgFile.getPath());
                            }

                            @Override
                            public void onError(Throwable e) {
                            }
                        }).launch();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadNewFile(File imgFile,String fileTime,long titleIndex,String filePath) {
        Map<String,Object> imageMap = new HashMap<>();
        imageMap.put("createTime", fileTime);
        imageMap.put("platform", Build.BRAND + " " + Build.MODEL);

        RequestBody requestBody;
        if (imgFile.getPath().endsWith(".mp4") || imgFile.getPath().endsWith(".mov")) {
            requestBody = RequestBody.create(MediaType.parse("video/*"), imgFile);

            MediaMetadataRetriever retr = new MediaMetadataRetriever();
            retr.setDataSource(imgFile.getPath());
            String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); // 视频高度
            String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);

            imageMap.put("width",width + "");
            imageMap.put("height",height + "");


        }else {
            requestBody = RequestBody.create(MediaType.parse("image/*"), imgFile);

            Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getPath());

            if (bitmap != null) {
                imageMap.put("width",bitmap.getWidth() + "");
                imageMap.put("height",bitmap.getHeight() + "");
                bitmap.recycle();
            } else {
                try {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(imgFile.getPath(), options);
                    options.inSampleSize = 1;
                    options.inJustDecodeBounds = false;
                    int w = options.outWidth;
                    int h = options.outHeight;
                    imageMap.put("width", w + "");
                    imageMap.put("height", h + "");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        try {
            String filename = URLEncoder.encode(imgFile.getName(), "UTF-8");

            MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, requestBody);

            Map<String,RequestBody> map = new HashMap<>();

            map.put("description",RequestBody.create(MediaType.parse("multipart/form-data"), "检测图片"));

            map.put("ossBucketName",RequestBody.create(MediaType.parse("multipart/form-data"), "SERVICE_PIC"));

            imageMap.put("workBaseId",mView.providerWorkBaseId());

            NetWorkHttp.getApi().uploadFileAws(map,fileBody,imageMap)
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .compose(mView.bindToLife())
                    .subscribe(new HttpCallBack<AwsFileBean>() {
                        @Override
                        protected void onDone(AwsFileBean awsFileBean) {
                            if (awsFileBean != null){
                                saveOrUpdateWorkResource(awsFileBean.id,titleIndex,true,filePath);
                            }
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {
                            saveOrUpdateWorkResource(0,titleIndex,true,filePath);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void obtainAloneBean() {
        NetWorkHttp.getApi().obtainAloneBean(mView.providerWorkBaseId(), mView.providerToSystemId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<AloneNewBean>() {
                    @Override
                    protected void onDone(AloneNewBean aloneBeans) {
                        /**
                         * 将网络上获取的购物车数据 存储到本地
                         */
                        if (aloneBeans != null) {
                            mView.showCurrenMiles(aloneBeans.currentMiles,aloneBeans.perMiles);
                        }

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }
    @Override
    public void getServiceBaseListLike(long questionBaseId, long questionOptionId, long workBaseId, long titleIndex, String decTitle,List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean.QuestionCarMilesDeductionEntityListBean> deductionList) {
        NetWorkHttp.getApi().getServiceBaseListLike(questionBaseId,questionOptionId,workBaseId)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<TestRecommendBean>>() {
                    @Override
                    protected void onDone(List<TestRecommendBean> list) {
                        mView.getServiceBaseListLikeSus(list, questionBaseId,  titleIndex, decTitle, questionOptionId,deductionList);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });


    }

    @Override
    public void getItemHotComment(long questionBaseId) {
        NetWorkHttp.getApi().showCommonComments(questionBaseId)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.<X3BaseCallModel<List<String>>>defaultComposeRequest())
                .subscribe(new HttpCallBack<List<String>>() {
                    @Override
                    protected void onDone(List<String> comments) {
                        mView.showItemHotCommentSuc(comments);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void submitAloneData(List<AloneNewBean.ItemQuestionListBean> aloneTyreBeans,long soundId) {
        NetWorkHttp.getApi().obtainQuestionList(mView.providerWorkBaseId(),aloneTyreBeans,mView.providerContent(),soundId)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.<X3BaseCallModel<Object>>defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        mView.showSuccessDialog();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

}
